package com.springboot.service;

import com.springboot.common.base.ResponseResult;
import com.springboot.common.util.DateUtils;
import com.springboot.entity.UserEntity;
import com.springboot.enums.ExchangeEnum;
import com.springboot.enums.QueueEnum;
import com.springboot.job.UserAddJob;
import com.springboot.repository.UserRepository;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;
import java.util.UUID;


@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private QueueMessageService queueMessageService;

    public UserEntity save(UserEntity entity) throws Exception{
        UserEntity user = userRepository.save(entity);

        buildCreateUserTimer();

        buildCreateGoodTimer();

        queueMessageService.send(user.getId(), ExchangeEnum.USER_REGISTER, QueueEnum.USER_REGISTER);


        return user;
    }

    public List<UserEntity> list() {
        return userRepository.findAll();
    }

    /**
     * 构建创建商品定时任务
     */
    public void buildCreateUserTimer() throws Exception {
        //设置开始时间为1分钟后
        long startAtTime = System.currentTimeMillis() + 1000 * 60;
        //任务名称
        String name = UUID.randomUUID().toString();
        //任务所属分组
        String group = UserAddJob.class.getName();
        //创建任务
        JobDetail jobDetail = JobBuilder.newJob(UserAddJob.class).withIdentity(name, group).build();
        //创建任务触发器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group).startAt(DateUtils.addSeconds(60)).build();
        //将触发器与任务绑定到调度器内
        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * 构建创建商品定时任务
     */
    public void buildCreateGoodTimer() throws Exception {
        //设置开始时间为1分钟后
        long startAtTime = System.currentTimeMillis() + 1000 * 60;
        //任务名称
        String name = UUID.randomUUID().toString();
        //任务所属分组
        String group = UserAddJob.class.getName();

        //任务触发器cron
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/30 * * * * ?");

        //创建任务
        JobDetail jobDetail = JobBuilder.newJob(UserAddJob.class).withIdentity(name, group).build();
        //创建任务触发器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group).withSchedule(cronScheduleBuilder).build();
        //将触发器与任务绑定到调度器内
        scheduler.scheduleJob(jobDetail, trigger);
    }
}
